<template>
  <el-card>
    <div class="card-header">
      <span>入库单列表</span>
    </div>
  </el-card>
  <el-card>
    <el-form :inline="true" :model="listForm">
      <el-form-item label="起始日期">
        <el-date-picker
            v-model.number="listForm.start_time"
            type="date"
            value-format="X"
            placeholder="选择起始日期"
        />
      </el-form-item>
      <el-form-item label="截至日期">
        <el-date-picker
            v-model.number="listForm.end_time"
            type="date"
            value-format="X"
            placeholder="选择截至日期"
        />
      </el-form-item>
      <el-form-item label="">
        <perms-button
            perms="stockin:receipt:list"
            :type="Types.success"
            :plain="true"
            @action="list"/>
      </el-form-item>
      <el-form-item label="">
        <perms-button
            perms="stockin:receipt:add"
            :type="Types.primary"
            :plain="true"
            @action="showDialog('add')"/>
      </el-form-item>
    </el-form>
    <el-table :data="stockins" :border="true">
      <template #empty>
        <el-empty/>
      </template>
      <el-table-column prop="supplier_name" label="供货商" min-width="100"/>
      <el-table-column label="货运状态" min-width="50" align="center" width="90">
        <template #default="scope">
          <el-tag :type="statusType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="入库日期" width="130" align="center">
        <template #default="scope">
          <span v-if="scope.row.status === 1">-</span>
          <span v-else>{{ timeFormat(scope.row.date) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="has_tax" label="含税" width="90" align="center">
        <template #default="scope">
          <el-tag :type="taxType(scope.row.has_tax)">{{ hasTax(scope.row.has_tax) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="tax" label="税率(%)" width="90">
        <template #default="scope">
          {{ scope.row.tax }}%
        </template>
      </el-table-column>
      <el-table-column prop="total" label="总金额(元)" width="130"/>
      <el-table-column prop="deposit" label="定金(元)" width="130"/>
      <el-table-column label="尾款状态" width="90" align="center">
        <template #default="scope">
          <el-tag :type="balanceType(scope.row.balance_status)">{{ balanceText(scope.row.balance_status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column lable="原材料" min-width="250">
        <template #default="scope">
          <el-tag v-for="(item, index) in scope.row.list" :key="index" :type="randType(index)"
                  style="margin-bottom: 10px">{{ item.material_name }} / {{ item.material_types }} / {{ item.weight }}吨
            / 单价:{{ item.price }}元 / 总价:{{ (item.weight * item.price).toFixed(3) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="260">
        <template #default="scope">
          <perms-button
              perms="stockin:receipt:update"
              :type="Types.primary"
              :size="Sizes.default"
              :plain="true"
              @action="showDialog('update', scope.row)"/>
          <el-popconfirm
              :icon="InfoFilled"
              icon-color="#F56C6C"
              :title='`确认删除当前入库单？`'
              cancel-button-text="取消"
              confirm-button-text="确认删除"
              cancel-button-type="info"
              confirm-button-type="danger"
              @confirm="remove(scope.row.id)"
              width="300"
          >
            <template #reference>
              <perms-button
                  perms="stockin:receipt:update"
                  :type="Types.danger"
                  :size="Sizes.default"
                  :plain="true"/>
            </template>
          </el-popconfirm>
          <el-popconfirm
              :icon="InfoFilled"
              icon-color="#eebe77"
              :title='`确认更改尾款状态？`'
              cancel-button-text="未付"
              confirm-button-text="已付"
              cancel-button-type="info"
              confirm-button-type="warning"
              @cancel="handleBalanceStatus(scope.row.id, false)"
              @confirm="handleBalanceStatus(scope.row.id, true)"
              width="300"
          >
            <template #reference>
              <perms-button
                  perms="stockin:receipt:balance"
                  :type="Types.warning"
                  :size="Sizes.default"
                  :plain="true"/>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="page"
        v-model:current-page="listForm.page"
        v-model:page-size="listForm.size"
        :page-sizes="[30, 40, 50, 100]"
        :disabled="loading"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list"
        @current-change="list"
    />
    <el-dialog
        :close-on-click-modal="false"
        v-model="visible"
        :title="dialogTitle"
        @close="list"
        :draggable="true"
        width="1200px">
      <el-form :model="stockinForm" ref="stockinRef" :rules="rules" label-width="120px">
        <el-form-item label="货运状态">
          <el-switch
              v-model="stockinForm.status"
              inactive-text="预定"
              active-text="到货"
              :inactive-value="1"
              :active-value="2"
          />
        </el-form-item>
        <el-form-item label="入库日期" prop="date" v-if="stockinForm.status !== 1">
          <el-date-picker
              v-model.number="stockinForm.date"
              type="date"
              value-format="X"
              placeholder="选择原材料入库日期"
          />
        </el-form-item>
        <el-form-item label="原材料供货商">
          <el-select v-model="stockinForm.supplier_id" autocomplete="off" clearable>
            <el-option :value="0" label=" " v-show="false"/>
            <el-option v-for="(supplier,idx) in supplierList" :label="supplier.name" :value="supplier.id" :key="idx"/>
          </el-select>
        </el-form-item>
        <el-form-item label="定金" prop="deposit">
          <el-input v-model.number="stockinForm.deposit" autocomplete="off" style="width: 200px"/>
          元
        </el-form-item>
        <el-form-item label="是否含税">
          <el-switch
              v-model="stockinForm.has_tax"
              active-text="是"
              inactive-text="否"
              :active-value="true"
              :inactive-value="false"
          />
        </el-form-item>
        <el-form-item label="税率(%)" v-if='stockinForm.has_tax'>
          <el-input-number v-model="stockinForm.tax" :min="0" :max="100" :precision="1" :step="1" :controls="false" autocomplete="off"/>
          %
        </el-form-item>
        <el-form-item label="添加原材料">
          <el-button icon="Plus" type="warning" plain @click="addMaterial"></el-button>
        </el-form-item>
        <el-form-item v-for="(item, index) in stockinForm.list" :label="`原材料 ${index+1}`" :key="index">
          <el-select v-model="stockinForm.list[index].materials_id" filterable autocomplete="off" clearable
                     placeholder="原材料"
                     style="width: 300px;padding-right: 10px">
            <el-option :value="0" label=" " v-show="false"/>
            <el-option v-for="(item,idx) in materialList" :label="item.name+' / '+item.types" :value="item.id"
                       :key="idx"/>
          </el-select>
          单价(元):
          <el-input-number v-model="stockinForm.list[index].price" placeholder="单价(元)" :precision="2" :step="100" :controls="false"
                           clearable style="margin:0 10px"/>
          数量(吨):
          <el-input-number v-model="stockinForm.list[index].weight" placeholder="数量(吨)" :precision="3" :step="1" :controls="false"
                           clearable style="width: 180px;margin:0 10px"/>
          <el-button icon="Close" type="danger" plain @click="stockinForm.list.splice(index, 1)"></el-button>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {StockInBalanceR, StockInListR} from "@/api/stockin";
import {ListRequest, AddRequest, StockInBalanceRequest, RemoveRequest} from "@/interface/stockin";
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {StockInAddR, StockInRemoveR, StockInUpdateR} from "@/api/stockin";
import dayjs from 'dayjs';
import {InfoFilled} from "@element-plus/icons-vue";
import {SupplierListR} from "@/api/suppliers";
import {MaterialListR} from "@/api/materials";
import PermsButton from '@/components/PermsButton.vue'
import {Sizes, Types} from "@/interface/enum";

//加载标识
const loading = ref<boolean>(false)
//dialog标识
const visible = ref<boolean>(false)
//动作标识
const action = ref<string>('')
const stockins = ref<AddRequest>()
const total = ref<Number>(0)
const dialogTitle = ref<string>('')

//表单校验
const stockinRef = ref<FormInstance>()

const initStockInForm = () => {
  return <AddRequest>{
    id: 0,
    supplier_id: 0,
    status: 1, //1.预定；2.到货
    balance_status: false, //尾款状态：true.已付；false.未付
    date: 0,
    has_tax: false,
    tax: 0,
    deposit: 0,
    list: [],
  }
}



//表单：列表
const listForm = reactive<ListRequest>({page: 1, size: 30})
//表单：添加
const stockinForm = ref<AddRequest>(initStockInForm())

const rules = reactive<FormRules>({
  deposit: [
    {required: true, message: '请填写定金', type: "number", trigger: ['blur', 'change']},
    {min: 0, message: '定金不能小于0', type: "number", trigger: ['blur', 'change']}
  ],
  date: [
    {required: true, message: '请选择入库日期', type: "number", min: 1, trigger: ['blur', 'change']},
  ],
})

//入库单列表
const list = () => {
  loading.value = true
  StockInListR(listForm).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      stockins.value = res.data.list as AddRequest
      total.value = res.data.total
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}

//showDialog
const showDialog = (act: string, row?: AddRequest) => {
  action.value = act
  switch (act) {
    case 'add':
      dialogTitle.value = '添加入库单'
      stockinForm.value = initStockInForm()
      visible.value = true
      break
    case 'update':
      dialogTitle.value = '修改入库单'
      stockinForm.value = row as AddRequest
      visible.value = true
      break
    default:
      ElMessage.warning('未知操作')
  }
}

//提交
const handleSubmit = () => {
  switch (action.value) {
    case 'add':
      add()
      break
    case 'update':
      update()
      break
    default:
      ElMessage.warning('未知操作')
  }
}

//添加入库单
const add = () => {
  loading.value = true
  StockInAddR(stockinForm.value).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      visible.value = false
      ElMessage.success('入库单添加成功')
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}

//删除入库单
const remove = (id: number) => {
  loading.value = true
  let req = <RemoveRequest>{id:id}
  StockInRemoveR(req).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success('入库单删除成功')
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}


//修改入库单信息
const update = () => {
  stockinRef.value?.validate((isValid)=>{
    if(!isValid){
      return
    }

    loading.value = true
    StockInUpdateR(stockinForm.value).then(res => {
      loading.value = false
      return res.data
    }).then(res => {
      if (res.code === 200) {
        visible.value = false
        list()
        ElMessage.success('入库单修改成功')
      } else {
        //ElMessage.error(res.msg)
      }
    }).catch(err => {
      loading.value = false
      console.log('err:', err)
    })
  })

}

//patch：更新入库单尾款状态
const handleBalanceStatus = (stock_id:number, balance_status:boolean) => {
  let req = <StockInBalanceRequest>{
    id: stock_id,
    balance_status: balance_status
  }
  StockInBalanceR(req).then(res=>{
    return res.data
  }).then(res => {
    if (res.code === 200) {
      list()
    }
  }).catch(err => {
    console.log('更新入库单尾款状态:'+JSON.stringify(err))
  })
}

//时间格式
const timeFormat = (timestamp: number) => {
  // return dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss')
  return dayjs.unix(timestamp).format('YYYY-MM-DD')
}


type Supplier = {
  id: number,//供货商id
  name: string//供货商名称
  supplier_id: number,//供货商
  has_tax: boolean,//是否含税
  tax: number,//税率(%)
}
//供货商列表
const supplierList = ref<Supplier[]>()
const suppliers = () => {
  loading.value = true
  SupplierListR({page: 1, size: 300}).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      supplierList.value = res.data.list as Supplier[]
      total.value = res.data.total
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}

type Material = {
  id: number,//原材料id
  name: string,//原材料规格
  types: string//原材料材质
}
//原材料列表
const materialList = ref<Material[]>()
const materials = () => {
  loading.value = true
  MaterialListR({page: 1, size: 300}).then(res => {
    loading.value = false
    return res.data
  }).then(res => {
    if (res.code === 200) {
      materialList.value = res.data.list as Material[]
      total.value = res.data.total
    } else {
      //ElMessage.error(res.msg)
    }
  }).catch(err => {
    loading.value = false
    console.log('err:', err)
  })
}


//添加原材料
const addMaterial = () => {
  stockinForm.value.list.push({
    materials_id: 0,
    material_name: '',
    material_types: '',
    weight: 0,
    price: 0,
  })
}

//货运状态
const statusText = (status: number) => {
  switch (status) {
    case 1:
      return '预定'
    case 2:
      return '到货'
    default:
      return '未知'
  }
}

const statusType = (status: number) => {
  switch (status) {
    case 1:
      return 'danger'
    case 2:
      return 'success'
    default:
      return 'info'
  }
}

//尾款状态
const balanceText = (has: boolean) => {
  switch (has) {
    case true:
      return '已付'
    case false:
      return '未付'
  }
}
const balanceType = (has: boolean) => {
  switch (has) {
    case true:
      return 'success'
    case false:
      return 'danger'
  }
}

//是否含税
const hasTax = (has: boolean) => {
  switch (has) {
    case true:
      return '是'
    case false:
      return '否'
  }
}
const taxType = (has: boolean) => {
  switch (has) {
    case true:
      return 'danger'
    case false:
      return ''
  }
}
const randType = (index: number) => {
  index %= 5
  switch (index) {
    case 0:
      return ''
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'danger'
    case 4:
      return 'info'
  }
}


onMounted(() => {
  suppliers()
  materials()
  list()
})

</script>

<style scoped>
.el-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page {
  margin-top: 10px;
}
</style>

